package com.zhentao.config;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.SetBucketPolicyArgs;
import jakarta.annotation.PostConstruct;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;



/**
 * MinIO配置类
 * 用于初始化MinIO客户端和创建必要的存储桶
 */
@Configuration
@Data
public class MinioConfig {

    private static final Logger logger = LoggerFactory.getLogger(MinioConfig.class);

    @Value("${minio.endpoint:http://8.145.55.161:19000}")
    private String endpoint;

    @Value("${minio.access-key:wzw347951752}")
    private String accessKey;

    @Value("${minio.secret-key:wzw347951752}")
    private String secretKey;

    @Value("${minio.bucket.face-images:face-images}")
    private String faceImagesBucket;

    @Value("${minio.bucket.chat-images:chat-images}")
    private String chatImagesBucket;

    @Value("${minio.bucket.chat-videos:chat-videos}")
    private String chatVideosBucket;

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 创建MinIO客户端Bean
     */
    @Bean
    public MinioClient minioClient() {
        return MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
    }

    /**
     * 初始化MinIO存储桶
     */
    @PostConstruct
    public void initializeBuckets() {
        try {
            MinioClient client = applicationContext.getBean(MinioClient.class);

            // 创建人脸图片存储桶
            createBucketIfNotExists(client, faceImagesBucket);

            // 创建聊天图片存储桶
            createBucketIfNotExists(client, chatImagesBucket);

            // 创建聊天视频存储桶
            createBucketIfNotExists(client, chatVideosBucket);

            logger.info("MinIO存储桶初始化完成 - 人脸图片桶: {}, 聊天图片桶: {}, 聊天视频桶: {}",
                       faceImagesBucket, chatImagesBucket, chatVideosBucket);

        } catch (Exception e) {
            logger.error("MinIO存储桶初始化失败", e);
        }
    }

    /**
     * 创建存储桶（如果不存在）
     */
    private void createBucketIfNotExists(MinioClient client, String bucketName) {
        try {
            // 检查存储桶是否存在
            boolean exists = client.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());

            if (!exists) {
                // 创建存储桶
                client.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
                logger.info("创建MinIO存储桶: {}", bucketName);

                // 设置存储桶策略（允许公共读取）
                String policy = createPublicReadPolicy(bucketName);
                client.setBucketPolicy(SetBucketPolicyArgs.builder()
                        .bucket(bucketName)
                        .config(policy)
                        .build());

                logger.info("设置存储桶 {} 为公共读取", bucketName);
            } else {
                logger.info("MinIO存储桶 {} 已存在", bucketName);
            }

        } catch (Exception e) {
            logger.error("创建MinIO存储桶 {} 失败", bucketName, e);
        }
    }

    /**
     * 创建公共读取策略
     */
    private String createPublicReadPolicy(String bucketName) {
        return "{\n" +
                "  \"Version\": \"2012-10-17\",\n" +
                "  \"Statement\": [\n" +
                "    {\n" +
                "      \"Effect\": \"Allow\",\n" +
                "      \"Principal\": {\n" +
                "        \"AWS\": \"*\"\n" +
                "      },\n" +
                "      \"Action\": \"s3:GetObject\",\n" +
                "      \"Resource\": \"arn:aws:s3:::" + bucketName + "/*\"\n" +
                "    }\n" +
                "  ]\n" +
                "}";
    }


}
